use std::env;
use crate::{commands, daemon};
use crate::sync;
use crate::cli::{Cli,Commands,DaemonAction};
use anyhow::{Context, Result};
use clap::{Parser, Subcommand };
use clap::error::ErrorKind ;
use crate::config::Config;
use tracing::{debug,info} ;
use crate::log;
use crate::utils::* ;
#[derive(Debug)]
pub struct App {
    cli: Cli,
}

impl App {
    pub fn new() -> Self {
        let cli = match Cli::try_parse() {
            Ok(c) => c ,
            Err(e) => {

                if e.kind() == ErrorKind::DisplayHelp || e.kind() == ErrorKind::DisplayVersion { // 如果是正常的显示帮助的命令  这里不应该拦截
                    e.exit();
                }
                let unknown_cmd : String = env::args().skip(1).collect::<Vec<String>>().join(" ") ;
                let all_commands = all_subcommand_names() ;
                let suggestions = find_similar_commands(&unknown_cmd, &all_commands, 3);
                eprintln!("❌ 未识别命令 {unknown_cmd}, 详细尝试 --help");
                if !suggestions.is_empty() {
                    eprintln!("\n最相似的命令是:");
                    for s in suggestions {
                        eprintln!("    {}", s);
                    }
                }
                std::process::exit(1);

            }
        } ;
        Self {
            cli,
        }
    }

    pub fn run(&self) -> Result<()> {
        match &self.cli.command {
            Commands::Init { force } => {
                commands::handle_init(force)?
            }
            Commands::Push { name, delete_source } => {
                commands::handle_push(name , delete_source) ?
            }
            Commands::Pull { name } => {
                commands::handle_pull(name , &false)?
            }
            Commands::Rsync {name , direction, delete_source , dry_run } => {
                commands::handle_rsync(name , direction , delete_source , dry_run)?
            }
            Commands::Remove{name} => {  // 移除配置文件的映射
                commands::handle_remove(name)?
            }
            Commands::List => {
                commands::handle_list() ?
            }
            Commands::Daemon { action } => {
                commands::handle_daemon(action) ?
            }
            Commands::Config{action } => {
                commands::handle_config(action) ?
            }
            Commands::Add{name} => {
                commands::handle_add(&name) ?
            }
        }
        Ok(())
    }
}